<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script src="./dict.js"></script>
    <script src="./queue.js"></script>
    <script src="./stack.js"></script>
    <script>
        class Graph {
            //属性: 顶点（数组）/ 边（字典）
            constructor() {
                this.vertexes = []; //顶点 
                this.edges = new Dictionay(); //边 
            }
            //方法 
            //添加方法 
            //1.添加顶点的方法  
            addVertex(v) {
                this.vertexes.push(v)
                this.edges.set(v, [])
            }
            //2.添加边的方法 
            addEdge(v1, v2) {
                this.edges.get(v1).push(v2); //v1通向v2 
                this.edges.get(v2).push(v1); //由于是无向图 同时v2要通向v1 
            }
            //3.实现toString方法 
            toString() {
                //1.定义字符串，保存最终的结果 
                var resultString = "";
                //2.遍历所有的顶点，以及顶点对应的边 

                // console.log(this.vertexes); 
                for (let i = 0; i < this.vertexes.length; i++) {
                    // console.log(this.vertexes[i] + "->" + this.edges.get(this.vertexes[i])); 
                    resultString += this.vertexes[i] + "->" + this.edges.get(this.vertexes[i]) + "\n"
                }
                return resultString;
                // console.log(resultString); 
            }
            //初始化状态颜色
            initializeColor() {
                var colors = [];
                for (var i = 0; i < this.vertexes.length; i++) {
                    colors[this.vertexes[i]] = 'white'
                }
                return colors;
            }
            //广度优先搜索(BFS)
            bfs(initV, handler) {
                //1.初始化颜色
                var colors = this.initializeColor();
                //2.创建队列
                var queue = new Queue();
                //3.将顶点加入到队列中
                queue.enqueue(initV);
                //4.循环从队列中取出我们的元素
                while (!queue.isEmpty()) {
                    //4.1从队列中取出一顶点
                    var v = queue.dequeue();
                    //4.2获取和顶点相连的边
                    var vList = this.edges.get(v)
                    //4.3将v的颜色设置成灰色
                    colors[v] = 'gray'
                    //4.4遍历所有的顶点并且加入到队列中
                    for (var i = 0; i < vList.length; i++) {
                        // queue.enqueue(vList[i])
                        var e = vList[i]
                        if (colors[e] === 'white') {
                            colors[e] = 'gray';
                            queue.enqueue(e);
                        }
                    }
                    //4.5 访问顶点
                    handler(v);
                    //4.6 将我们的顶点设置为黑色
                    colors[v] = 'black'
                }
            }
            //广度优先搜索最短距离
            bfsDistances(initV) {
                //1.初始化颜色
                var colors = this.initializeColor();
                //2.创建队列 创建距离 创建前溯点
                var queue = new Queue();
                var distances = {};
                var predecessors = {}; //前溯用来表示路径
                for (let i = 0; i < this.vertexes.length; i++) {
                    distances[this.vertexes[i]] = 0;
                    predecessors[this.vertexes[i]] = null;
                }
                //3.将顶点加入到队列中
                queue.enqueue(initV);
                //4.循环从队列中取出我们的元素
                while (!queue.isEmpty()) {
                    //4.1从队列中取出一顶点
                    var v = queue.dequeue();
                    //4.2获取和顶点相连的边
                    var vList = this.edges.get(v)
                    //4.3将v的颜色设置成灰色
                    colors[v] = 'gray'
                    //4.4遍历所有的顶点并且加入到队列中
                    for (var i = 0; i < vList.length; i++) {
                        // queue.enqueue(vList[i])
                        var e = vList[i]
                        if (colors[e] === 'white') {
                            colors[e] = 'gray';
                            distances[e] = distances[v] + 1;
                            predecessors[e] = v;
                            queue.enqueue(e);
                        }
                    }
                    //4.5 访问顶点
                    // handler(v);
                    //4.6 将我们的顶点设置为黑色
                    colors[v] = 'black'
                }
                return { distances, predecessors }
            }
            //深度优先搜索(DFS)
            dfs(initV, handler) {
                //1.初始化颜色
                var colors = this.initializeColor();
                //2.从某个顶点开始依次递归访问
                this.dfsVisit(initV, colors, handler)
            }
            dfsVisit(v, colors, handler) {    //递归函数
                //1.先将颜色设置为灰色
                colors[v] = 'gray'
                //2.处理v顶点
                handler(v);
                //3.访问v相连的顶点
                var vList = this.edges.get(v);
                for (var i = 0; i < vList.length; i++) {
                    var e = vList[i];
                    if (colors[e] === 'white') {
                        this.dfsVisit(e, colors, handler);
                    }
                }
                //4.将v设置成黑色
                colors[v] = 'black'
            }

            //探索深度优先
            exploreDFS() {
                //1.初始化颜色
                var colors = this.initializeColor();
                const d = {};
                const f = {};
                const p = {};
                const time = { count : 0 };
                for(let i = 0; i < this.vertexes.length; i++){
                    f[this.vertexes[i]] = 0;
                    d[this.vertexes[i]] = 0;
                    p[this.vertexes[i]] = null;
                }
                for(let i = 0; i < this.vertexes.length; i++){
                    if(colors[this.vertexes[i]] === 'white') {
                        this.exploreDFSVisit(this.vertexes[i],colors,d,f,p,time,this.edges)//递归
                    }
                }
                return {
                    distances:d,
                    finished:f,
                    predecessors:p
                }
            }
            exploreDFSVisit(v,colors,d,f,p,time,edges) {    //递归函数
                //1.先将颜色设置为灰色
                colors[v] = 'gray'
                d[v] = ++time.count;
                //3.访问v相连的顶点
                var vList = edges.get(v);
                for (var i = 0; i < vList.length; i++) {
                    var e = vList[i];
                    if (colors[e] === 'white') {
                        p[e] = v;
                        this.exploreDFSVisit(e,colors,d,f,p,time,this.edges)
                    }
                }
                //4.将v设置成黑色
                colors[v] = 'black';
                f[v] = ++time.count;
            }
        }

        //1。创建图结构
        let graph = new Graph();
        // graph.addVertex("a"); 
        // graph.addVertex("b"); 
        // graph.addVertex("c"); 
        // graph.addEdge("a", "b"); 
        // graph.addEdge("a", "c"); 
        // console.log(graph); 
        //2.添加顶点 
        var myVertexes = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
        for (let i = 0; i < myVertexes.length; i++) {
            graph.addVertex(myVertexes[i])
        }
        //3.添加边
        graph.addEdge("A", "B")
        graph.addEdge("A", "C")
        graph.addEdge("A", "D")
        graph.addEdge("C", "D")
        graph.addEdge("C", "G")
        graph.addEdge("D", "G")
        graph.addEdge("D", "H")
        graph.addEdge("B", "E")
        graph.addEdge("B", "F")
        graph.addEdge("E", "I")
        ////打印图
        // console.log(graph);

        ////图表格 
        alert(graph)
        //测试bfs
        // var result = '';
        // graph.bfs(graph.vertexes[0], function (v) {
        //     result += v + ' '
        // });
        // alert(result);

        ////到各个点的最短距离 路径 bfs
        // const fromVertex = myVertexes[0];
        // const predecessors = graph.bfsDistances(graph.vertexes[0]).predecessors;
        // for (let i = 1; i < myVertexes.length; i++) {
        //     var toVertex = myVertexes[i];
        //     const path = new Stack();
        //     for (let v = toVertex; v != fromVertex; v = predecessors[v]) {
        //         path.push(v);
        //     }
        //     path.push(fromVertex);
        //     let s = path.pop();
        //     while (!path.isEmpty()) {
        //         s += '-' + path.pop();
        //     }
        //     console.log(s);
        // }

        // //测试dfs
        var result2 = '';
        graph.dfs(graph.vertexes[0], (v) => {
            result2 += v + ' '
            console.log(v);
        })
        // alert(result2)
        ////测试exploreDFS
        // console.log(graph.exploreDFS());
        
        

        

    </script>
</body>

</html>